// import { commonUtils } from '@utils/common';
class StorageUtils {
  constructor(prefix) {
    this.prefix = prefix;
  }

  /**
   * 私有方法获取key
   * @param {string} key
   * @returns {string}
   */
  getKey(key) {
    return `${this.prefix}:${key}`;
  }

  /**
   * 设置缓存配置(秒级)
   * @param time
   * @returns {{prefix: string, storeTime: number}}
   */
  setOptions(time) {
    // 如果用户没传递时间进来就是一天
    if (time && time > 0) {
      time = new Date().getTime() + 1000 * time;
    } else {
      time = new Date().getTime() + 1000 * 60 * 60 * 24;
    }
    return {
      storeTime: time,
      prefix: this.prefix
    };
  }

  /**
   * 设置这是一个异步本地存储
   * @param {string} key
   * @param {*}value
   * @param {number} time
   */
  setLocalItem(key, value, time = 7 * 24 * 60 * 60) {
    const _key = this.getKey(key);
    const options = this.setOptions(time);
    try {
      uni.setStorageSync(_key, JSON.stringify({
        options,
        value
      }));
    } catch (e) {
      // commonUtils.toast(e)
    }
  }

  /**
   * 获取本地存储
   * @param {string} key
   */
  getLocalItem(key) {
    const _key = this.getKey(key);
    try {
      const storeData = uni.getStorageSync(_key);
      if (storeData) {
        const {
          value,
          options: { storeTime }
        } = JSON.parse(storeData);
        // 如果从存储中获取的时间大于当前的时间或者等于0的时候表示当前的localStorage有效
        if (storeTime > new Date().getTime()) {
          return value;
        }
        uni.removeStorageSync(_key);
        return null;
      }
      return null;
    } catch (e) {
      // commonUtils.toast(e)
      return false;
    }
  }

  /**
   * 清除本地缓存
   * @param {string} key
   */
  removeLocalItem(key) {
    const _key = this.getKey(key);
    const value = this.getLocalItem(key);
    if (value) {
      try {
        uni.removeStorageSync(_key);
      } catch (e) {
        // commonUtils.toast(e)
      }
    }
  }

  /**
   * 清空存储
   */
  clear() {
    try {
      uni.clearStorageSync();
    } catch (e) {
      // error
    }
  }
}
export const storageUtils = new StorageUtils('Zander_Phone');
